package financial.sharing.center.invoice.service.impl;

import financial.sharing.center.common.enums.ResponseContext;
import financial.sharing.center.common.utils.BigDecimalUtil;
import financial.sharing.center.invoice.dao.InvoiceDetailMapper;
import financial.sharing.center.invoice.feign.SystemFeignTestService;
import financial.sharing.center.invoice.model.entity.Invoice;
import financial.sharing.center.invoice.model.entity.InvoiceDetail;
import financial.sharing.center.invoice.service.InvoiceDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName InvoiceDetailServiceImpl
 * @Description TODO
 * @Author guoyuhang
 * @ @csdn https://blog.csdn.net/qq_40788718
 * @Date 2021/5/19
 * @Version 1.0
 */
@Service
public class InvoiceDetailServiceImpl implements InvoiceDetailService {

    @Autowired
    private InvoiceDetailMapper invoiceDetailMapper;

    @Autowired
    private SystemFeignTestService systemFeignTestService;

    @Override
    public InvoiceDetail getInvoiceDetail(Invoice invoice) {
        Example example = new Example(InvoiceDetail.class);
        example.createCriteria().andEqualTo("invoiceId", invoice.getId());
        return this.invoiceDetailMapper.selectOneByExample(example);
    }

    @Override
    public Integer createOneInvoiceDetail(InvoiceDetail invoiceDetail) {
        int i = this.invoiceDetailMapper.insert(invoiceDetail);
        return i == 1 ? ResponseContext.成功.getValue() : ResponseContext.创建失败.getValue();
    }

    @Override
    public Integer compileOneInvoiceDetail(InvoiceDetail invoiceDetail) {

        int i = this.invoiceDetailMapper.updateByPrimaryKey(invoiceDetail);
        return i == 1 ? ResponseContext.成功.getValue() : ResponseContext.删除失败.getValue();
    }

    @Override
    public Map<Integer, BigDecimal> getMapInvoiceDetail() {
        List<InvoiceDetail> invoiceDetailList = this.invoiceDetailMapper.selectAll();
        Map<Integer, BigDecimal> taxRateMap = this.systemFeignTestService.getTaxRateMap();
        Map<Integer,BigDecimal> result = new HashMap<>();
        for (InvoiceDetail invoiceDetail : invoiceDetailList) {
            if (invoiceDetail.getTaxRateId() != null){
                BigDecimal totalTaxMoney = invoiceDetail.getTotalMoney().multiply(taxRateMap.get(invoiceDetail.getTaxRateId())).add(invoiceDetail.getTotalMoney());
                result.put(invoiceDetail.getInvoiceId(), totalTaxMoney);
            }else{
                result.put(invoiceDetail.getInvoiceId(), BigDecimalUtil.ZERO);
            }
        }
        return result;
    }
}
